package report

import (
	"fmt"
	"time"

	"github.com/shirou/gopsutil/v3/cpu"
	"gopkg.in/yaml.v2"
)

type _cpuInfo struct {
	CPU        int32    `json:"cpu" yaml:"cpu"`
	VendorID   string   `json:"vendorId" yaml:"vendorId"`
	Family     string   `json:"family" yaml:"family"`
	Model      string   `json:"model" yaml:"model"`
	Stepping   int32    `json:"stepping" yaml:"stepping"`
	PhysicalID string   `json:"physicalId" yaml:"physicalId"`
	CoreID     string   `json:"coreId" yaml:"coreId"`
	Cores      int32    `json:"cores" yaml:"cores"`
	ModelName  string   `json:"modelName" yaml:"modelName"`
	Mhz        float64  `json:"mhz" yaml:"mhz"`
	CacheSize  int32    `json:"cacheSize" yaml:"cacheSize"`
	Flags      []string `json:"flags" yaml:"flags"`
	Microcode  string   `json:"microcode" yaml:"microcode"`
}

type CPUInfo struct {
	Count   int        `json:"count" yaml:"count"`
	Precent float64    `json:"precent" yaml:"precent"`
	Info    []_cpuInfo `json:"info" yaml:"info"`
}

func FetchCpuInfo() CPUInfo {
	var info CPUInfo

	// cpu数量
	cpuCount, err := cpu.Counts(false)
	if err != nil {
		info.Count = 0
	} else {
		info.Count = cpuCount
	}

	// percent
	cpuPercent, err2 := cpu.Percent(2*time.Second, false)
	if err2 != nil {
		info.Precent = 0
	} else {
		info.Precent = cpuPercent[0]
	}

	// cpu info

	is, err3 := cpu.Info()
	if err3 != nil {
		info.Info = nil
	} else {
		for _, is2 := range is {
			var _info _cpuInfo
			_info.CPU = is2.CPU
			_info.VendorID = is2.VendorID
			_info.Family = is2.Family
			_info.Model = is2.Model
			_info.Stepping = is2.Stepping
			_info.PhysicalID = is2.PhysicalID
			_info.CoreID = is2.CoreID
			_info.Cores = is2.Cores
			_info.ModelName = is2.ModelName
			_info.Mhz = is2.Mhz
			_info.CacheSize = is2.CacheSize
			_info.Flags = is2.Flags
			_info.Microcode = is2.Microcode
			info.Info = append(info.Info, _info)
		}
	}

	return info
}

func (c *CPUInfo) Show() {

	out, err := yaml.Marshal(c)
	if err != nil {
		fmt.Printf("格式化CPU信息失败: %v\n", err)

	}
	fmt.Println(string(out))
}
